

<template>
  <PlusDialogForm
      ref="plusFormInstance"
      v-model:visible="dialogShow"
      v-model="formData"
      :form="{ group:columns, cardProps:{ shadow:'never' }, colProps:{ span:12 },  labelWidth:'110px',  labelPosition:'right',  rules:formRules }"
      :dialog="{ title: dialogTitle, width: '940px', top: '12vh', confirmLoading }"
      @confirm="handleSubmit"
      @cancel="handleCancel"
  >
    <template #plus-field-emergency>
      <div class="flex justify-end  w-full pb5">
        <el-button size="small" type="primary" @click="addEmergency">添加</el-button>
      </div>
      <el-table :data="formData.emergency">
        <el-table-column label="联系人姓名">
          <template #default="{row,$index}">
            <el-form-item label="" :prop="`emergency[${$index}].contactName`">
              <el-input placeholder="请输入" v-model="row.contactName"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="关系">
          <template #default="{row,$index}">
            <el-form-item label="" :prop="`emergency[${$index}].contactRelation`">
              <el-select v-model="row.contactRelation">
                <el-option v-for="item in edu_emergency_relation" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="联系方式">
          <template #default="{row,$index}">
            <el-form-item label="" :prop="`emergency[${$index}].contactPhone`">
              <el-input placeholder="请输入" v-model="row.contactPhone"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{row,$index}">
            <el-button type="danger" link @click="formData.emergency.splice($index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </PlusDialogForm>
</template>


<script setup>
import { getStudentApi, addStudentApi, updateStudentApi } from "@/api/edutation/student";
import { getCurrentInstance,ref } from "vue"
import {useCommonData} from "@/hooks/useCommonData.js";
const { proxy } = getCurrentInstance();
const { sys_user_sex,edu_student_state,edu_emergency_relation } = proxy.useDict('edu_emergency_relation','sys_user_sex','edu_student_state');

const primaryKey = "studentId"  // 主键
const emit = defineEmits(["update"]);
const {
  schoolDataList,getSchoolDataList,
  professionalDataListBySchoolId,getProfessionalDataListBySchoolId,
  classDataList,getClassDataList,
  campusDataList,getCampusDataList
} = useCommonData();

getSchoolDataList();


const dialogShow = ref(false);
const confirmLoading = ref(false)
const isEdit = computed(() =>!!formData.value[primaryKey])
const dialogTitle = computed(() => (isEdit.value ? '编辑' : '新增')+'学生')
const plusFormInstance = ref(null);
const formInstance = computed(()=>plusFormInstance.value?.formInstance)
const columns = computed(()=>[
  {
    title:"基本信息",
    columns:[
      {
        label: '学生姓名',
        prop: 'studentName',
        valueType:'input',
        fieldProps:{
          maxlength: 200,
          modelModifiers: { trim: true },
        },
      },
      {
        label: '曾用名',
        prop: 'oldName',
        valueType:'input',
        fieldProps:{
          maxlength: 200,
          modelModifiers: { trim: true },
        },
      },
      {
        label: '性别',
        prop: 'gender',
        valueType:'select',
        options:sys_user_sex.value,
        optionsMap:{},
      },
      {
        label: '联系电话',
        prop: 'phone',
        valueType:'input',
        fieldProps:{
          maxlength: 200,
          modelModifiers: { trim: true },
        },
      },
      {
        label: '出生日期',
        prop: 'birthday',
        valueType:'input',
        fieldProps:{
          maxlength: 200,
          modelModifiers: { trim: true },
        },
      },
      {
        label: '身份证号码',
        prop: 'idCard',
        valueType:'input',
        fieldProps:{
          maxlength: 200,
          modelModifiers: { trim: true },
        },
      },
      {
        label: '户籍地址',
        prop: 'cardAddress',
        valueType:'textarea',
        colProps:{
          span:24
        },
        fieldProps:{
          maxlength: 200,
          showWordLimit: true,
          modelModifiers: { trim: true },
        },
      },
      {
        label: '现居住地址',
        prop: 'houseAddress',
        valueType:'textarea',
        colProps:{
          span:24
        },
        fieldProps:{
          maxlength: 200,
          showWordLimit: true,
          modelModifiers: { trim: true },
        },
      },

    ]
  },
  {
    title:"学籍信息",

    columns: [
      {
        label: '学生学号',
        prop: 'studentNumber',
        valueType:'input',
        fieldProps:{
          maxlength: 200,
          modelModifiers: { trim: true },
        },
      },
      {
        label: '学生状态',
        prop: 'state',
        valueType:'select',
        options:edu_student_state.value,
        fieldProps:{
        },
      },
      {
        label: '归属学校',
        prop: 'schoolId',
        valueType:'select',
        options:schoolDataList.value,
        optionsMap:{
          label:'schoolName',
          value:'schoolId',
        },
        fieldProps:{
          onChange(value){
            formData.value.proId = ''
            formData.value.classId = ''
            formData.value.campusId = ''
            getProfessionalDataListBySchoolId(value);
            getClassDataList({ schoolId:value });
            getCampusDataList({ schoolId:value })
          }
        },
      },
      {
        label: '归属专业',
        prop: 'proId',
        valueType:'select',
        options:professionalDataListBySchoolId.value,
        optionsMap:{
          label:'proName',
          value:'proId',
        },
        fieldProps:{
        },
      },
      {
        label: '归属班级',
        prop: 'classId',
        valueType:'select',
        options:classDataList.value,
        optionsMap:{
          label:'className',
          value:'classId',
        },
        fieldProps:{
        },
      },
      {
        label: '归属校区',
        prop: 'campusId',
        valueType:'select',
        options:campusDataList.value,
        optionsMap:{
          label:'campusName',
          value:'campusId',
        },
        fieldProps:{
          maxlength: 200,
          modelModifiers: { trim: true },
        },
      },
    ]
  },
  {
    title:"紧急联系人信息",
    columns: [
      {
        label: '紧急联系人',
        prop: 'emergency',
        valueType:'textarea',
        colProps:{
          span:24
        },
        fieldProps:{
          maxlength: 200,
          showWordLimit: true,
          modelModifiers: { trim: true },
          autosize: { minRows: 2, maxRows: 4 }
        },
      },
    ]
  },
  {
    title:"其他信息",

    columns: [
      {
        label: '备注',
        prop: 'remark',
        valueType:'textarea',
        colProps:{
          span:24
        },
        fieldProps:{
          maxlength: 200,
          showWordLimit: true,
          modelModifiers: { trim: true },
          autosize: { minRows: 2, maxRows: 4 }
        },
      },
    ]
  }
])
const formData = ref({
  remark: "",
  studentNumber: "",
  oldName: "",
  idCard: "",
  phone: "",
  schoolId: "",
  campusId: "",
  birthday: "",
  cardAddress: "",
  houseAddress: "",
  emergency: [],
  state: "",
  gender: "",
  studentName: ""
});
const formRules = ref({
  studentNumber: [{ required: true, message: "学号不能为空", trigger: ["blur"] }],
  oldName: [{ required: true, message: "学校编码不能为空", trigger: ["blur"] }],
  idCard: [{ required: true, message: "身份证号码不能为空", trigger: ["blur"] }],
  phone: [{ required: true, message: "联系电话不能为空", trigger: ["blur"] }],
  schoolId: [{ required: true, message: "归属学校不能为空", trigger: ["blur"] }],
  campus: [{ required: true, message: "归属校区不能为空", trigger: ["blur"] }],
  birthday: [{ required: true, message: "归属校区不能为空", trigger: ["blur"] }],
  cardAddress: [{ required: true, message: "户籍地址不能为空", trigger: ["blur"] }],
  houseAddress: [{ required: true, message: "现居住地址不能为空", trigger: ["blur"] }],
  emergency: [{ required: true, message: "紧急联系人不能为空", trigger: ["blur"] }],
  state: [{ required: true, message: "学生状态不能为空", trigger: ["blur"] }],
  gender: [{ required: true, message: "性别不能为空", trigger: ["blur","change"] }],
  studentName: [{ required: true, message: "学生姓名不能为空", trigger: ["blur"] }]
});

// 添加紧急联系人
const addEmergency = ()=>{
  formData.value.emergency.push({
    contactName:'',
    contactPhone:'',
    contactRelation:'',
  })
}

// 确定按钮操作
const handleSubmit = async () => {
  try {
    confirmLoading.value = true
    const { emergency, ...data } = formData.value;
    data.emergency = JSON.stringify(emergency || [])
    if (isEdit.value) {
      await updateStudentApi(data)
      proxy.$modal.msgSuccess("修改成功")
    } else {
      await addStudentApi(data)
      proxy.$modal.msgSuccess("新增成功")
    }
    handleCancel();
    emit('update')
  } catch (error) {
    console.warn('提交错误:', error)
  } finally {
    confirmLoading.value = false
  }
}

// 取消按钮操作
function handleCancel() {
  dialogShow.value = false
  onReset();
}

// 重置数据
const onReset = () => {
  formData.value = {
    remark: "",
    studentNumber: "",
    oldName: "",
    idCard: "",
    phone: "",
    schoolId: "",
    campusId: "",
    birthday: "",
    cardAddress: "",
    houseAddress: "",
    emergency: [],
    state: "",
    gender: "",
    studentName: ""
  }
  formInstance.value.resetFields();
}
// 查询回显
const getDetail = async (key) => {
  const { data } = await  getStudentApi(key)
  try {
    data.emergency = JSON.parse(data.emergency)
  } catch (e){
    data.emergency = []
  }
  const { schoolId } = data;
  formData.value = data;
  await getProfessionalDataListBySchoolId(schoolId);
  await getClassDataList({ schoolId });
  await getCampusDataList({ schoolId })
}
// 打开弹框
const openDialog = async (row) => {
  if(row && row[primaryKey]){
    await getDetail(row[primaryKey])

  }
  dialogShow.value = true;
};
defineExpose({ openDialog });
</script>


